import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo } from '@/api/modules/user'
import type { LoginData, UserInfo } from '../types/user'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
  }

  // 清除token
  const clearToken = () => {
    token.value = ''
  }

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
  }

  const clearUserInfo = () => {
    userInfo.value = null
  }

  const loginUser = async (data: LoginData) => {
    try {
      const res: any = await login(data)
      setToken(res.data.token)
      // 登录成功后获取用户信息
      await fetchUserInfo()
      return res
    } catch (error) {
      throw error
    }
  }


  const fetchUserInfo = async () => {
    const res = await getUserInfo()
    if (res.code === 1000 && res.data) {
      const apiUserInfo = res.data
      // Transform API response to store UserInfo type
      const storeUserInfo: UserInfo = {
        id: apiUserInfo.id,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        tenantId: null,
        unionid: '',
        avatarUrl: apiUserInfo.avatar,
        nickName: apiUserInfo.username,
        username: apiUserInfo.username,
        phone: '',
        gender: 0,
        status: 1,
        loginType: 1,
        description: null,
        erpBusinessId: '',
        realName: '',
        address: '',
        telephone: null,
        areaName: '',
        levelId: '',
        isPres: '0',
        discount: apiUserInfo.discount
      }
      setUserInfo(storeUserInfo)
    }
    return res
  }

  const logout = () => {
    clearToken()
    clearUserInfo()
  }

  return {
    token,
    userInfo,
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    loginUser,
    fetchUserInfo,
    logout
  }
}, {
  persist: true
}) 